package com.wanxi.tcp.demo5客户端发送图片给服务器;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * TCP服务器端，服务器端接收客户端上传的字节文件文件
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        System.out.println("tcp 服务端启动.....");
        //1. 创建服务器端socket
        ServerSocket serverSocket = new ServerSocket(40000);

        System.out.println("等待客户端的连接....");
        while (true) {
            //2 建立客户端soket通道,阻塞形式
            Socket socket = serverSocket.accept();
            System.out.println("客户端上传文件了.....");
            //3 创建输入流 建立soket通道,阻塞形式
            InputStream inputStream = socket.getInputStream();
            //4 接收上传的信息
            int content = -1;
            // 创建本地文件输出流
//            String fileName = UUID.randomUUID().toString();
            String fileName = System.currentTimeMillis() + "";
            String path = "day22网络编程基础/src/com/wanxi/tcp/demo5客户端发送图片给服务器";
            OutputStream fileOutputStream = new FileOutputStream(new File(path + "/" + fileName + ".gif"));
            System.out.println("读取客户端文件内容开始保存.....");
            while ((content = inputStream.read()) != -1) {
                fileOutputStream.write(content);
            }
            // 上传完成后，给客户端一个消息，上传成功
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bufferedWriter.write("上传成功");
            bufferedWriter.newLine();
            bufferedWriter.flush();
            bufferedWriter.close();

            //释放资源
            fileOutputStream.close();
            socket.close();

            System.out.println("客户端文件保存完毕，文件路径为：" + "file/" + fileName + ".gif");
        }
    }
}
